<template>
	<div class="file-compare">
		<div class="base-view">
			<el-upload class="upload-file" action="/api/file/upload" :limit="2" :before-upload="beforeUpload" :on-success="handleFileSuccess" :on-remove="handleRemove" multiple :on-exceed="handleExceed" :auto-upload="true">
				<el-button slot="trigger" icon="el-icon-upload2" size="small" type="primary">文件上传</el-button>
			</el-upload>
			<el-button v-if="doingFlag" icon="el-icon-loading" class="btn-compare" size="small" type="success" @click="compare"> 开始对比 </el-button>
			<el-button v-else icon="el-icon-tickets" class="btn-compare" size="small" type="success" @click="compare"> 开始对比 </el-button>
		</div>
		<div class="base-view">
			<h3><i class="el-icon-first-aid-kit" /> 对比字段</h3>
			<el-input v-model="columnName" type="text" maxlength="100" placeholder="请输入字段名称，以逗号为分隔符" show-word-limit clearable />
		</div>
		<div class="base-view">
			<div class="head">
				<h3><i class="el-icon-tickets" /> 对比结果</h3>
				<div class="export">
					<el-select v-model="selectedSheet" placeholder="请选择" @change="handleSheetChange">
						<el-option v-for="(sheetName, index) in sheetNames" :key="index" :label="sheetName" :value="index" />
					</el-select>
					<el-button @click="downloadFile"><i class="el-icon-download" /> 导出</el-button>
				</div>
			</div>
			<el-table v-loading="loading" :data="tableData" border style="width: 100%" fit highlight-current-row>
				<el-table-column v-for="(col, index) in tableColumn" :key="index" :prop="col" :label="col" show-overflow-tooltip :min-width="120" />
			</el-table>
			<div class="base-pagination">
				<el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :current-page="pageNum" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
	</div>
</template>
<script>
import API from "@/api";
import { download } from "@/utils/download";
export default {
	data() {
		return {
			fileList: [],
			columnName: "",
			fileName: null,
			tableData: [],
			tableColumn: [],
			sheetNames: [],
			selectedSheet: null,
			timer: null,
			pageSize: 10,
			total: 0,
			pageNum: 1,
			doingFlag: false,
			loading: false,
			uuid: "",
			status: false
		};
	},
	beforeDestroy() {
		// 清除定时器
		clearInterval(this.timer);
		this.timer = null;
	},
	methods: {
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制选择 2 个文件，共选择了 ${files.length + fileList.length} 个文件`);
		},
		beforeUpload(file) {
			const fileType = ["xlsx", "xls", "csv"];
			const isTrue = fileType.some(type => file.name.split(".")[1] === type);
			if (!isTrue) {
				this.$message.warning("上传文件仅支持 xlsx、xls、csv 格式！");
				return false;
			}
			return true;
		},
		handleFileSuccess(response) {
			if (!response.success) {
				this.$message.error(response.message);
				return;
			}
			// 上传成功则修改列表
			this.fileList.push(response.data);
			this.$message.success(response.message);
		},
		handleRemove(file) {
			// 文件列表中移除操作删除的文件
			this.fileList = this.fileList.filter(item => item !== file.response.data);
		},
		compare() {
			if (this.fileList.length !== 2) {
				this.$message.warning("必须上传两个文件!");
				return;
			}

			API.comare({ filesName: this.fileList, columns: this.columnName })
				.then(response => {
					this.doingFlag = true;
					this.$message.success(response.message);
					this.uuid = response.data;
					// 启动定时器
					this.startScheduleTimer();
				})
				.catch(() => {
					this.doingFlag = false;
					this.$message.error("Error，服务端异常");
				});
		},
		downloadFile() {
			if (this.fileName === null) {
				this.$message.warning("暂无数据！");
				return;
			}
			API.download({ fileName: this.fileName }).then(response => {
				download.download(new Blob([response]), this.fileName);
			});
		},
		handleSheetChange(index) {
			// 操作页码后，重新选择sheet，需要重置当前页面
			this.pageNum = 1;
			this.showExcelData(index);
		},
		showExcelData(sheetNo) {
			this.loading = true;
			API.getTableData({ fileName: this.uuid, sheetNo, pageNum: this.pageNum, pageSize: this.pageSize })
				.then(resp => {
					this.tableData = resp.data.tableData;
					this.total = resp.data.total;
					this.tableColumn = resp.data.tableColumn;
					this.sheetNames = ["file1-file2", "file2-file1", "file1+file2"];
					this.loading = false;
				})
				.catch(() => {
					this.loading = false;
					this.$message.error("Error，服务端异常");
				});
		},
		// 异步文件对比，同行触发定时器每隔5秒请求,请求成功更新table
		startScheduleTimer() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			this.timer = setInterval(() => {
				API.queryStatus({ fileName: this.uuid }).then(resp => {
					if (resp.success && resp.data.status === 1) {
						this.status = resp.data.status;
						this.doingFlag = false;
						clearInterval(this.timer);
						this.timer = null;
						// 默认读取第一个sheet
						this.selectedSheet = "file1-file2";
						this.showExcelData(0);
					} else if (resp.errCode && resp.errMsg) {
						this.$message(resp.errMsg);
						clearInterval(this.timer);
						this.timer = null;
					}
				});
			}, 5000);
		},
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.pageNum = 1;
			this.showExcelData(this.selectedSheet);
		},
		handleCurrentChange(pageNum) {
			this.pageNum = pageNum;
			this.showExcelData(this.selectedSheet);
		}
	}
};
</script>

<style lang="scss" scoped>
.file-compare {
	.btn-compare {
		display: inline-block;
		position: absolute;
		top: 16px;
		left: 130px;
	}
}
.head {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.export {
		margin-right: 10px;
	}
}
</style>
